package control.panel
{
	import events.ItemEvent;
	
	import flash.events.MouseEvent;
	
	import model.room.ItemData;
	
	import view.panel.item.ItemButton;
	import view.panel.item.ItemShortcutPanel;
	import view.panel.prompt.msg.ItemShortCutMsg;

	public class ItemShortcutPanelControl extends PanelControl
	{
		private var items:Array = [];
		
		public function ItemShortcutPanelControl()
		{
			initPanel();
			initListeners();
		}
		
		private function initPanel():void
		{
			_view.itemShortCutPanel = new ItemShortcutPanel(this);
		}
		
		public function initListeners():void
		{
			_model.itemModel.addEventListener(ItemEvent.ITEM_ARRIVAL,onItemArrival);
			_model.itemModel.addEventListener(ItemEvent.ITEM_USE_RESULT,onItemUseResult);
		}
		
		private function onItemUseResult(event:ItemEvent):void
		{
			var item:ItemButton;
			for each (item in items)
			{
				if (item.id == event.itemId)
				{
					item.count = event.count;
					return;
				}
			}
		}
		
		private function onItemArrival(event:ItemEvent):void
		{
			clear();
			var itemDatas:Array = event.itemDatas;
			var itemData:ItemData;
			var index:int=0;
			for (var i:int=0;i<itemDatas.length;i++)
			{
				itemData = itemDatas[i];
				if (itemData.index == -1)
				{
					continue;
				}
				
				//var item:ItemButton = new ItemButton(i* 32,3,itemData.id,onItem,30,30,"butBg",itemData.image);
				var item:ItemButton = new ItemButton(index* 32 + 3,3,itemData.id,onItem,30,30,"butBg","face_item_" + itemData.id);
				index ++;
				item.count = itemData.count;
				item.info = itemData.desc;
				_view.itemShortCutPanel.addItem(item);
				
				items.push(item);
				_model.traceManager.out("item name:",itemData.id);
			}
			
			_view.tableLayer.addChild(_view.itemShortCutPanel);
			_model.traceManager.out("item shortCut:",itemDatas.length);
		}
		
		private function onItem(event:MouseEvent):void
		{
			var count:int = event.target.count;
			if (count <= 0)
			{
				var hintMsg:ItemShortCutMsg = new ItemShortCutMsg();
				_control.alertYesNoPanelControl.open(hintMsg);
			}
			else
			{
				_model.netRemote.useItem(event.target.id.toString());
			}
		}
		
		private function clear():void
		{
			_view.itemShortCutPanel.clear();
			
			for each (var item:ItemButton in items)
			{
				item.destroy();
			}
			items.length = 0;
		}
	}
}